package com.ys.controller.api.eKnowAi;

import com.alibaba.fastjson.JSONObject;
import com.ys.config.MyConfig;
import com.ys.entity.eKnowAi.*;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.service.eKnowAi.EKnowKnowledgeBaseService;
import com.ys.util.baidu.ApiHttpClientUtils;
import com.ys.util.shiro.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/knowledgeBase")
public class ApiInterKnowledgeBaseController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterKnowledgeBaseController.class);

	@Autowired
	private ApiHttpClientUtils apiHttpUtils;

	private static String URLAPI = MyConfig.getUrlApi1_5();

	@Autowired
	private EKnowKnowledgeBaseService eKnowKnowledgeBaseService;

	/**
	 * 获取知识库信息列表
	 */
	@PostMapping("/getKnowledgeBaseList")
	@ResponseBody
	public JSONObject getKnowledgeBaseList(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			List<EKnowKnowledgeBase> knowledgeList = new ArrayList<>();
			if(params!=null && params.get("knowledgeName")!=null && !"".equals(params.get("knowledgeName"))){
				knowledgeList = new EKnowKnowledgeBase().where("A.KnowledgeBaseName LIKE '%"+params.get("knowledgeName")+"%'").setOrderby("A.Sort ASC").queryList();
			}else {
				knowledgeList = new EKnowKnowledgeBase().setOrderby("A.Sort ASC").queryList();
			}
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			result.put("knowledgeList", knowledgeList);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道获取知识库信息列表出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 *	查询知识库信息
	 */
	@PostMapping("/searchKnowledgeBaseById")
	@ResponseBody
	public JSONObject searchKnowledgeBaseById(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			long id = Long.parseLong(params.get("id").toString());//知识库Id
			EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase().setId(id).queryFirst();
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			result.put("eKnowKnowledgeBase", eKnowKnowledgeBase);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("查询知识库信息出错：",e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 新增、修改知识库信息
	 */
	@PostMapping("/addOrUpdateKnowledgeBase")
	@ResponseBody
	public JSONObject addOrUpdateKnowledgeBase(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			String loginUserId = ShiroUtils.getUserId();//登录的用户ID

			EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase();
			eKnowKnowledgeBase.setUpdateUserId(loginUserId);
			eKnowKnowledgeBase.setKnowledgeBaseName(params.get("knowledgeBaseName").toString());
			eKnowKnowledgeBase.setKnowledgeBaseDescribe(params.get("knowledgeBaseDescribe").toString());
			eKnowKnowledgeBase.setSort(Integer.parseInt(params.get("sort").toString()));
			int isSave = 0;
			if(params.get("addOrUpdate").toString().equals("add")){//新增
				Map<String, Object> sendParams = new HashMap<>();
				sendParams.put("add","add");
				String sentUrl = URLAPI + "/api/outer/baiDuEKnowAi/addKnowledgeBase";
				//向量数据库新增索引库
				JSONObject addBack = apiHttpUtils.sendHttpPost(sendParams,sentUrl);
				if(addBack.get("indexName")!=null){
					eKnowKnowledgeBase.setESIndexName(addBack.get("indexName").toString());
					eKnowKnowledgeBase.setStatus(0);
					isSave = eKnowKnowledgeBaseService.addKnowledgeBase(eKnowKnowledgeBase);
				}
			}else {//修改
				eKnowKnowledgeBase.setId(Long.parseLong(params.get("knowledgeBaseId").toString()));
				eKnowKnowledgeBase.setStatus(1);
				isSave = eKnowKnowledgeBaseService.updateKnowledgeBase(eKnowKnowledgeBase);
			}
			if(isSave>0){
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道新增、修改知识库信息出错：",e.getMessage(),e);
		}
		return result;
	}



	/**
	 * 删除知识库
	 */
	@PostMapping("/delOrUpdateKnowledgeBase")
	@ResponseBody
	public JSONObject delOrUpdateKnowledgeBase(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){

		JSONObject result = new JSONObject();
		try {
			long id = Long.parseLong(params.get("id").toString());

			//判断资料是否为空
			List<EKnowKnowledgeList> hasList = new EKnowKnowledgeList().setBaseId(id).queryList();
			if(hasList!=null && hasList.size()>0){
				result.put("code", EknowCodeEnum.ApiRetuenCode.CANNOT);
				return result;
			}
			//判断是否绑定场景
			List<EKnowSceneKnowledge> hasList2 = new EKnowSceneKnowledge().setKnowledgeBaseId(id).queryList();
			if(hasList2!=null && hasList2.size()>0){
				result.put("code", EknowCodeEnum.ApiRetuenCode.HASSCENE);
				return result;
			}
			//判断是否有分类信息未清空
			List<EKnowKnowledgeType> hasList3 = new EKnowKnowledgeType().setBaseId(id).queryList();
			if(hasList3!=null && hasList3.size()>0){
				result.put("code", EknowCodeEnum.ApiRetuenCode.HASTYPENODEL);
				return result;
			}


			int isDel = 0;
			EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase().setId(id).queryFirst();
			if(eKnowKnowledgeBase!=null){
				Map<String, Object> sendParams = new HashMap<>();
				sendParams.put("indexName",eKnowKnowledgeBase.getESIndexName());
				String sentUrl = URLAPI + "/api/outer/baiDuEKnowAi/delKnowledgeBase";
				//向量数据库新增索引库
				JSONObject addBack = apiHttpUtils.sendHttpPost(sendParams,sentUrl);
				if(addBack.get("indexName")!=null){
					isDel = eKnowKnowledgeBaseService.delKnowledgeBase(id);
				}
				if(isDel>0){
					result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
				}else {
					result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
				}
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
				return result;
			}

		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道删除知识库出错：",e.getMessage(),e);
		}
		return result;

	}



}